package models

import (
	"fly/schema"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

type SysDept struct {
	BaseModel
	Name string `orm:"column(name);description(名称)"`
	Pid  int64  `orm:"column(pid);description(上级ID，一级菜单为0)"`
	Pids string `orm:"column(pids);description(所有上级ID，用逗号分开)"`
	Sort int    `orm:"column(sort);description(排序)"`
}

func init() {
	orm.RegisterModel(new(SysDept))
}

// SearchField 定义模型的可搜索字段
func (*SysDept) SearchField() []string {
	return []string{"name", "pid", "status"}
}

// WhereField 定义模型可作为条件的字段
func (*SysDept) WhereField() []string {
	return []string{"id", "status", "name", "pid"}
}

// SimpleField 简略查询字段
func (*SysDept) SimpleField() []string {
	return []string{"id", "name", "pid"}
}

func (m *SysDept) TableName() string {
	return "sys_dept"
}

// AddSysDept insert a new SysDept into database and returns
// last inserted Id on success.
func AddSysDept(m *SysDept, userId int64) (id int64, err error) {
	o := orm.NewOrm()
	m.Creator = userId
	m.Updater = userId
	id, err = o.Insert(m)
	return
}

// GetSysDeptById retrieves SysDept by Id. Returns error if
// Id doesn't exist
func GetSysDeptById(id int64) (v *SysDept, err error) {
	o := orm.NewOrm()
	v = &SysDept{BaseModel: BaseModel{Id: id}}
	if err = o.QueryTable(new(SysDept)).Filter("id", id).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateSysDeptById updates SysDept by Id and returns error if
// the record to be updated doesn't exist
func UpdateSysDeptById(m *SysDept, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysDept{BaseModel: BaseModel{Id: m.Id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Updater = userId
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSysDept deletes SysDept by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSysDept(id int64) (err error) {
	o := orm.NewOrm()
	v := SysDept{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SysDept{BaseModel: BaseModel{Id: id}}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// DestroySysDept Destroy SysDept by Id and returns error
func DestroySysDept(id int64, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysDept{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Status = schema.StatusDelete
		v.Updater = userId
		var num int64
		if num, err = o.Update(v, "updater", "status"); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}
